/**
 * @author of2470
 *@date 2017/4/26
 *@description
 */
import * as React from "react";
import { Relax } from "iflux2";
import { transNormalTime, getEnvXSite, openNewWin } from "x-site-util";
import { Table, Icon, Button, Popconfirm, message } from "antd";
import NewPadModal from "./new-pad-modal";
import { List, Map } from "immutable";
import { getSystemCodeZip } from "../../common/const-value";
import GaUtil from "common-util/ga-util";
import ExpireLock from "expire-lock";

const SystemCodeZip = getSystemCodeZip();
@Relax
export default class PageManageWx extends React.Component<any, any> {
  columns = [
    {
      title: "广告名称",
      dataIndex: "title",
      key: "title",
      width: "20%",
      render: (text, record, index) => {
        return (
          <div>
            {this.state.editing === index
              ? <input
                  defaultValue={text}
                  autoFocus={true}
                  onKeyPress={this._onKeyPressTitle.bind(this, record, index)}
                  onBlur={this._changeTitle.bind(this, record, index)}
                />
              : <div className="title-input">
                  <span>
                    {text || "页面标题"}
                  </span>
                  <a
                    href="javascript:;"
                    onClick={this._editTitle.bind(this, index)}
                  >
                    <Icon type="edit" />
                  </a>
                </div>}
          </div>
        );
      }
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: text =>
        <span>
          {text === "published" ? "已发布" : "未发布"}
        </span>
    },
    {
      title: "修改时间",
      dataIndex: "updateTime",
      key: "updateTime",
      render: text =>
        <span>
          {text && transNormalTime(text)}
        </span>
    },
    {
      title: "操作",
      dataIndex: "tplId",
      key: "action",
      width: "30%",
      render: (text, record, index) => {
        return (
          <span>
            {record.pageType !== "roulette"
              ? <a
                  href="javascript:;"
                  onClick={this._getEditUrl.bind(this, record)}
                >
                  编辑
                </a>
              : null}
            {this._showDelBtn(record)
              ? <span>
                  <span className="ant-divider" />
                  <Popconfirm
                    title="确定删除该广告？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={this._confirmDelete.bind(this, record)}
                  >
                    <a href="#">删除</a>
                  </Popconfirm>
                </span>
              : null}
            {record.pageType === "index" && record.activated
              ? <span>
                  <span className="ant-divider" />
                  <span>播放中</span>
                </span>
              : null}
            {record.pageType === "index" &&
            !record.activated &&
            record.status === "published"
              ? <span>
                  <span className="ant-divider" />
                  <Popconfirm
                    title="确定要播放该广告？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={this._confirmActivateIndex.bind(this, record)}
                  >
                    <a href="#" className="ant-dropdown-link">
                      点击播放
                    </a>
                  </Popconfirm>
                </span>
              : null}
          </span>
        );
      }
    }
  ];

  modal: any = {};

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      editing: ""
    };
  }

  static defaultProps = {
    totalCount: 0,
    pageSize: 0,
    pageNo: 1,
    pageTypeInfo: Map(),
    pageList: List(),
    platform: "",
    getPageList: () => {},
    deletePage: () => {},
    activateIndexPage: () => {},
    setPageTitle: () => {},
    getTemplateList: () => {},
    getPageTypeBtnList: () => {},
    copyPageInfo: () => {}
  };

  render() {
    const pageList = this.props.pageList;
    const columns = this.columns;
    let result;
    if (!this.props.loading && pageList.count() > 0) {
      let pagination = {
        total: this.props.totalCount,
        pageSize: this.props.pageSize,
        current: this.props.pageNo,
        onChange: this._changePage
      };
      result = (
        <Table
          dataSource={pageList.toJS()}
          columns={columns}
          pagination={pagination}
          style={{ marginTop: "10px", textAlign: "center" }}
        />
      );
    } else if (!this.props.loading) {
      result = (
        <div
          style={{
            marginTop: "200px",
            fontSize: "15px",
            padding: "6px",
            textAlign: "center"
          }}
        >
          <span
            style={{ color: "#ff9800", fontSize: "17px", paddingRight: "10px" }}
          >
            <Icon type="info-circle" />
          </span>
          <span>暂无广告，新建广告开始对您的客显站点进行装修吧！</span>
        </div>
      );
    }

    return (
      <div id="page-manage-content">
        <Button
          onClick={this._addNewPage.bind(this)}
          type="primary"
          size="large"
        >
          新增广告
        </Button>
        {result}
        <NewPadModal
          visible={this.state.visible}
          platform={this.props.platform}
          changeModalStatus={this._changeModalStatus}
        />
      </div>
    );
  }

  @ExpireLock()
  _getEditUrl(record) {
    let editURL = getEnvXSite() + record.editURL + "?sc=" + SystemCodeZip;
    openNewWin(editURL);
  }

  @ExpireLock()
  _editTitle(index) {
    GaUtil.addPageEvent({
      eventAction: "编辑广告名称",
      eventLabel: "",
      platform: this.props.platform
    });
    this.setState({ editing: index });
  }

  //在input输入框里点击enter
  _onKeyPressTitle = (record, index, e) => {
    if (e.charCode === 13) {
      this._changeTitle(record, index, e);
    }
  };

  //改变title
  _changeTitle = (record, index, e) => {
    let value = e.target.value;
    this.setState({ editing: "" });
    let length = this._getStrLength(value);
    if (length > 0 && length <= 20) {
      if (record.title !== value) {
        this.props
          .setPageTitle({
            pageType: record.pageType,
            pageCode: record.pageCode,
            platform: this.props.platform,
            title: value,
            index
          })
          .then(
            () => {
              message.success("修改广告名称成功！", 3);
            },
            err => {
              console.log(err);
              message.error("修改错误，请重试！", 3);
            }
          );
      }
    } else {
      message.error("广告名称不能为空并且长度不能超过20个字符！", 4);
    }
  };

  _getStrLength = str => {
    let reg = /[\u4e00-\u9fa5]/g;
    let chinese = str.match(reg) || [];
    let alphanumeric = str.replace(reg, "") || "";
    return chinese.length * 2 + alphanumeric.length;
  };

  //添加新页面  打开模态框
  @ExpireLock()
  async _addNewPage() {
    this.props.getPageTypeBtnList({
      platform: this.props.platform
    });
    await this.props.getTemplateList({
      includePageTypeList: ["index"],
      platform: this.props.platform
    });
    this._changeModalStatus(true);
    GaUtil.addPageEvent({
      eventAction: "点击新增广告",
      eventLabel: "",
      platform: this.props.platform
    });
  }

  //展示或者隐藏模态框
  _changeModalStatus = visible => {
    if (!visible) {
      this.props.getPageList({
        platform: this.props.platform,
        pageNo: 0,
        pageSize: this.props.pageSize
      });
    }
    this.setState({ visible });
  };

  //分页搜索
  _changePage = pageNo => {
    this.props.getPageList({
      platform: this.props.platform,
      pageNo: pageNo - 1,
      pageSize: this.props.pageSize
    });
  };

  //确认删除页面
  @ExpireLock()
  _confirmDelete(record) {
    GaUtil.addPageEvent({
      eventAction: "删除广告",
      eventLabel: record.tplCode,
      platform: this.props.platform
    });
    let num = (this.props.totalCount - 1) % this.props.pageSize;
    let pageNo = num > 0 ? this.props.pageNo - 1 : this.props.pageNo - 2;
    pageNo = pageNo < 0 ? 0 : pageNo;
    this.props
      .deletePage({
        platform: this.props.platform,
        pageType: record.pageType,
        pageCode: record.pageCode,
        pageSize: this.props.pageSize,
        pageNo
      })
      .then(() => {
        message.success("删除广告成功！");
      })
      .catch(err => {
        console.log(err);
        message.warn("删除广告失败！");
      });
  }

  //确认设为首页
  @ExpireLock()
  _confirmActivateIndex(record) {
    GaUtil.addPageEvent({
      eventAction: "设为播放页",
      eventLabel: record.tplCode,
      platform: this.props.platform
    });
    this.props
      .activateIndexPage({
        platform: this.props.platform,
        pageCode: record.pageCode,
        pageSize: this.props.pageSize
      })
      .then(() => {
        message.success("设为首页播放成功！");
      })
      .catch(err => {
        console.log(err);
        message.warn("设为首页播放失败！");
      });
  }

  //是否展示删除按钮
  _showDelBtn = pageInfo => {
    if (
      ("index" === pageInfo.pageType && pageInfo.activated) ||
      ["roulette"].indexOf(pageInfo.pageType) >= 0 ||
      ["classify", "goodsInfo", "goodsList", "service"].indexOf(
        pageInfo.pageCode
      ) >= 0 ||
      pageInfo.fakeData ||
      ("index" === pageInfo.pageType && this.props.indexCount === 1)
    ) {
      return false;
    } else {
      return true;
    }
  };
}
